import 'dart:async';

import 'package:flutter/widgets.dart';
import 'package:tencent_kit/tencent_kit.dart';

typedef TencentShareListener = void Function(TencentShareResp response);

class TencentBuilder extends StatefulWidget {
  final Tencent tencent;
  final WidgetBuilder builder;
  final TencentShareListener shareRespListener;

  final String appId;
  final String universalLink;

  const TencentBuilder({
    @required this.tencent,
    @required this.builder,
    this.shareRespListener,
    @required this.appId,
    this.universalLink,
  });

  @override
  State<StatefulWidget> createState() {
    return _TencentBuilderState();
  }
}

class _TencentBuilderState extends State<TencentBuilder> {
  StreamSubscription<TencentShareResp> _shareRespSubscription;

  @override
  void initState() {
    super.initState();

    widget.tencent.registerApp(
      appId: widget.appId,
      universalLink: widget.universalLink,
    );
    if (widget.shareRespListener != null) {
      _shareRespSubscription =
          widget.tencent.shareResp().listen(widget.shareRespListener);
    }
  }

  @override
  void dispose() {
    super.dispose();

    _shareRespSubscription?.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return widget.builder(context);
  }
}
